/* $RCSFile: HtmlTab.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/HTMLTab/HtmlTab.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:55  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.Web.Services.Protocols;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Authentication;

using AddonNice.Settings.PageModules.HtmlTab;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using AddonNice.Core;

namespace AddonNice.PageModules.HtmlTab 
{

 	#region Local TraceSwitch 
	public class HtmlTabTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("HtmlTabTrace","Special Trace Switch for HtmlTab");
	}
	#endregion Local TraceSwitch 

    #region const strings
    public class LStr
    {
        public const string TabsAlign               =	"MODULE_SETTINGS_HTMLTAB_ALIGN";
        public const string TabsOrientation         =	"MODULE_SETTINGS_HTMLTAB_ORIENTATION";
        public const string TabsMultiRow            =	"MODULE_SETTINGS_HTMLTAB_MULTIROW";
        public const string TabsScroll              =	"MODULE_SETTINGS_HTMLTAB_SCROLL";
        public const string TabsScrollPos           =	"MODULE_SETTINGS_HTMLTAB_SCROLLPOS";
        public const string UseMouseOver            =	"MODULE_SETTINGS_HTMLTAB_USEMOUSEOVER";
    }
    #endregion const strings
    
    
    /// <summary>
    /// Initializer class for HtmlTab 
    /// </summary>
    public class HtmlTabSI : PortalCRMModuleControlSI
    {
        public HtmlTabSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HtmlTabSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HtmlTabSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HtmlTabSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                               =   pm.ExtendedResourcesGroup;

            // Set Editor Settings 
			HtmlEditorDataType.AddEditorToSettings(bSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS,extgrp);
            
            SettingItemSpecial HorizTabs                =   new SettingItemSpecial(LStr.TabsOrientation,new ListDataType(typeof(TabStripOrientation)));
			HorizTabs.Order			                    =	10;
            HorizTabs.ExtendedGroupName                 =   extgrp;
            HorizTabs.Group                             =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            HorizTabs.Value			                    =	TabStripOrientation.HorizontalTop.ToString(); // default value
			HorizTabs.Description		                =	"Select the way you want to display Tabs";
            HorizTabs.EnglishName		                =	"Tabs Orientation";
			bSettings.AddSetting(HorizTabs);
            
            SettingItemSpecial TabsAlign                =   new SettingItemSpecial(LStr.TabsAlign,new ListDataType(typeof(TabStripAlign)));
			TabsAlign.Order			                    =	20;
            TabsAlign.ExtendedGroupName                 =   extgrp;
            TabsAlign.Group                             =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            TabsAlign.Value			                    =	TabStripAlign.Left.ToString(); // default value
			TabsAlign.Description		                =	"Select the way you want to align Tabs";
            TabsAlign.EnglishName		                =	"Tabs Align";
			bSettings.AddSetting(TabsAlign);
                        
            SettingItemSpecial TabsMultiRow             =   new SettingItemSpecial(LStr.TabsMultiRow,new BooleanDataType());
			TabsMultiRow.Order			                =	30;
            TabsMultiRow.ExtendedGroupName              =   extgrp;
            TabsMultiRow.Group                          =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            TabsMultiRow.Value			                =	StStr.strFalse; // default value
			TabsMultiRow.Description		            =	"Check to have multi-row tabs, you will have to set the breaks on ending line tabs";
            TabsMultiRow.EnglishName		            =	"Multi-row tabs";
			bSettings.AddSetting(TabsMultiRow);

            SettingItemSpecial TabsScroll               =   new SettingItemSpecial(LStr.TabsScroll,new BooleanDataType());
			TabsScroll.Order			                =	40;
            TabsScroll.ExtendedGroupName                =   extgrp;
            TabsScroll.Group                            =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            TabsScroll.Value			                =	StStr.strFalse; // default value
			TabsScroll.Description		                =	"Check to have scrolling tabs when a too large number of tabs exists";
            TabsScroll.EnglishName		                =	"Scrolling tabs";
			bSettings.AddSetting(TabsScroll);

            SettingItemSpecial UseMouseOver             =   new SettingItemSpecial(LStr.UseMouseOver,new BooleanDataType());
			UseMouseOver.Order			                =	45;
            UseMouseOver.ExtendedGroupName              =   extgrp;
            UseMouseOver.Group                          =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            UseMouseOver.Value			                =	StStr.strFalse; // default value
			UseMouseOver.Description		            =	"Check to have tabs changed on mouse over";
            UseMouseOver.EnglishName		            =	"Change on Mouse over";
			bSettings.AddSetting(UseMouseOver);

            SettingItemSpecial TabsScrollPos            =   new SettingItemSpecial(LStr.TabsScrollPos,new ListDataType(typeof(TabStripScrollButtonsPosition)));
			TabsScrollPos.Order			                =	50;
            TabsScrollPos.ExtendedGroupName             =   extgrp;
            TabsScrollPos.Group                         =   SettingItemGroup.MODULE_SPECIAL_SETTINGS;
            TabsScrollPos.Value			                =	TabStripScrollButtonsPosition.Right.ToString(); // default value
			TabsScrollPos.Description		            =	"If you selected scrolling, select the scrolling buttons position";
            TabsScrollPos.EnglishName		            =	"Scroll buttons position";
			bSettings.AddSetting(TabsScrollPos);

            if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]HtmlTabSI InitSettings END",(HtmlTabTrace.Sw.TraceVerbose) ? HtmlTabTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    ///	HtmlTab display prospects in a RadGrid.
    /// </summary>
	public partial class HtmlTab : PortalCRMModuleControl
    {
        HtmlTabDB tDB           =   new HtmlTabDB();
        bool isAdminPortal      =   Config.IsAdminPortal;

        #region General implementation

        /// <summary>
		/// AddonNice module key
		/// </summary>
		public override Guid GuidID
        {
            get
            {
               return new Guid("{5E303177-7FD3-4a17-A9CD-AA09A1592D6B}");
            }
        }
        
        /// <summary>
        /// General usage Module
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #endregion General implementation

        #region Local Properties


        /// <summary>
        /// Allows to transfer to RadTabStrip this parameter: center, justify, left, right
        /// Default left
        /// </summary>
        public TabStripAlign Align
        {
            get
            {
                string or   =   Settings[LStr.TabsAlign].Value;
                switch ( or )
                {
                    default:
                    case "Left":
                    return TabStripAlign.Left;
                    case "Right":
                    return TabStripAlign.Right;
                    case "Justify":
                    return TabStripAlign.Justify;
                    case "Center":
                    return TabStripAlign.Center;
                }
            }
        }

        /// <summary>
        /// Allows to transfer to RadTabStrip this parameter: HorizontalTop, HorizontalBottom,VerticalLeft,VerticalRight
        /// Default HorizontalTop
        /// </summary>
        public TabStripOrientation Orientation 
        {
            get
            {
                string or   =   Settings[LStr.TabsOrientation].Value;
                switch ( or )
                {
                    default:
                    case "HorizontalTop":
                    return TabStripOrientation.HorizontalTop;
                    case "HorizontalBottom":
                    return TabStripOrientation.HorizontalBottom;
                    case "VerticalLeft":
                    return TabStripOrientation.VerticalLeft;
                    case "VerticalRight":
                    return TabStripOrientation.VerticalRight;
                }
            }
        }

        /// TabStrip is vertical ? set according Orientation parameter
        /// </summary>
        public bool IsVertical
        {
            get
            {
                return (Orientation == TabStripOrientation.VerticalLeft ||
                            Orientation == TabStripOrientation.VerticalRight );
            }
        }


        #endregion local Properties

        #region Ctor

        /// <summary>
        /// Ctor allows settings to select an entity and its fields to localize
        /// </summary>
        public HtmlTab()
        {
            if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]HtmlTab Ctor BEG",(HtmlTabTrace.Sw.TraceVerbose ) ? HtmlTabTrace.Sw.Info :ModuleTraceSwitch.Sw.Info);
            if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]HtmlTab Ctor END",(HtmlTabTrace.Sw.TraceVerbose) ? HtmlTabTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                         =   "HTMLTAB";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new HtmlTabSI(bSettings,this);
        }

        #endregion Ctor
  
        protected void Page_Load(object sender, EventArgs e)
        {
           if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HtmlTab Page_Load BEG IsPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),( HtmlTabTrace.Sw.TraceVerbose ) ? HtmlTabTrace.Sw.Info :ModuleTraceSwitch.Sw.Info);
          
            //if( RadTabStrip1.Tabs.Count > 0 )
              //  MyTab                                   =   RadTabStrip1.InnermostSelectedTab.Text;

           if ( !IsPostBack )
           {
                RadTabStrip1.Align                      =   Align;
                RadTabStrip1.Orientation                =   Orientation;
                RadTabStrip1.ScrollChildren             =   Settings[LStr.TabsScroll].ToBool();
                if ( RadTabStrip1.ScrollChildren )
                    RadTabStrip1.ScrollButtonsPosition   =   (TabStripScrollButtonsPosition)Enum.Parse(typeof(TabStripScrollButtonsPosition),Settings[LStr.TabsScrollPos].ToString());
               BindTabs();
           }
           if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HtmlTab Page_Load END IsPostBack: {0}",IsPostBack),(HtmlTabTrace.Sw.TraceVerbose)? HtmlTabTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
         }

        #region Main methods
        void BindTabs()
        {
		    try
		    {
                int mid                     =   ModuleID;
                DataTable tb                =   tDB.GetTabsGlobalized(mid);
                RadTabStrip1.DataTextField  =   "Title";
                RadTabStrip1.DataValueField =   "ItemID";
                if ( IsEditable && isAdminPortal)
                {
                    DataRow rw              =   tb.NewRow();
                    rw["ItemID"]            =   -1;
                    rw["TabOrder"]          =   -1;
                    rw["IsBreak"]           =   false;
                    rw["Description"]       =   LocalizeHelper.Localize("HTMLTAB_FIRSTTAB","Admin Tab");
                    rw["Title"]             =   LocalizeHelper.Localize("HTMLTAB_NEWTAB","Add new");
                    tb.Rows.Add(rw);
                }
			    RadTabStrip1.DataSource	    =	tb;
			    RadTabStrip1.DataBind();

		    }
		    catch(Exception ex )
		    {
			    if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]HtmlTab Page_Load Time : {0}, ex : {1}",DateTime.UtcNow,ex),ModuleTraceSwitch.Sw.Info);
			    throw;
		    }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]HtmlTab Page_Load END.",ModuleTraceSwitch.Sw.Info);
        }

        void RadTabStrip1_TabDataBound(object sender,RadTabStripEventArgs e)
        {
            bool isdatarow              =    ((e.Tab.DataItem != null) && (e.Tab.DataItem is DataRowView ));
		    if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]HtmlTab RadTabStrip1_TabDataBound isDatarowView: {0}.",isdatarow),ModuleTraceSwitch.Sw.Info);
            if ( !isdatarow )
                return;
            RadPageView pg              =   new RadPageView();
            Label lbl                   =   new Label();
            DataRowView rw              =   (DataRowView)e.Tab.DataItem;
            int itID                    =   (int)rw["ItemID"];
            e.Tab.IsBreak               =   (bool)rw["IsBreak"];
            // in admin mode only, display order in tab title
            if ( isAdminPortal &&  IsEditable )
            {
                int TabOrder            =   (int)rw["tabOrder"];                 
                if ( TabOrder != -1 )
                    e.Tab.Text          =   string.Format("{0}({1})",e.Tab.Text,TabOrder); // in edit mode display the order in tab
                if ( itID == -1 )
                {
                    itID                =   0;
                     e.Tab.NavigateUrl  =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Config.ModulesPath+"/HtmlTab/HtmlTabEdit.aspx",PageID,string.Format("mid={0}",ModuleID));
                }
                else e.Tab.NavigateUrl  =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Config.ModulesPath+"/HtmlTab/HtmlTabEdit.aspx",PageID,string.Format("ItemID={0}&mid={1}",itID,ModuleID));
            }
            pg.ID                       =   string.Format("PgVw_{0}",itID);
            pg.CssClass                 =   string.Format("HtmlTabPageView {0}",(IsVertical) ? "HtmlTabVert": "HtmlTabHoriz");
            e.Tab.PageViewID            =   pg.ID;
            lbl.ID                      =   string.Format("Lbl_{0}",itID);
            lbl.Text                    =   HttpUtility.HtmlDecode((string)rw["Description"]);
            pg.Controls.Add(lbl);
            RadMultiPage1.PageViews.Add(pg);
        }

        #endregion Main methods


        #region Std Overrides

        protected override void OnPreRender(EventArgs e)
        {
            if ( !isAdminPortal && Settings[LStr.UseMouseOver].ToBool() )
            {
                RadTabStrip1.UnSelectChildren   =   true;
                RadTabStrip1.OnClientMouseOver  =   "SelectMyTab";
                //RadTabStrip1.ClickSelectedTab   =   true;
                //RadTabStrip1.AutoPostBack       =   true;
                //RadTabStrip1.OnClientMouseOut   =   "UnSelectMyTab";
            }
            base.OnPreRender(e);
        }

        override protected void OnInit(EventArgs e)
        {
            if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HtmlTab OnInit BEG.",(HtmlTabTrace.Sw.TraceVerbose) ? HtmlTabTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if ( HtmlTabTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]HtmlTab OnInit END.",(HtmlTabTrace.Sw.TraceVerbose) ? HtmlTabTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
 

        private void InitializeComponent()
        {
            Load                        +=  new System.EventHandler(this.Page_Load);
            RadTabStrip1.TabDataBound   +=  new RadTabStripEventHandler(RadTabStrip1_TabDataBound);
        }


        #endregion
        
    }
}